﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using STEM123.StemService;

namespace STEM123
{
    /// <summary>
    /// Allows a user to create slides of a presentation.
    /// </summary>
    public partial class CreateSlides : PhoneApplicationPage
    {
        #region Private members

        /// <summary>
        /// Selects current question for a slide.
        /// </summary>
        /// <param name="listBoxQuestions">List box of questions.</param>
        /// <param name="index">Index of slide.</param>
        private void selectQuestionOfSlide(ListBox listBoxQuestions, uint index)
        {
            string question = ExplainViewModel.Instance.Slides[index].Question;

            if (!string.IsNullOrEmpty(question))
            {
                for (int i = 0; i < listBoxQuestions.Items.Count; i++)
                {
                    if (string.Equals(listBoxQuestions.Items[i].ToString(), question))
                    {
                        // select question in listbox based on question of respective slide
                        listBoxQuestions.SelectedItem = listBoxQuestions.Items[i];
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Checks if media is allowed, given certain constraints.
        /// </summary>
        /// <param name="index">Index of slide.</param>
        /// <returns>True if more audio / video is allowed else false.</returns>
        private bool isMoreMediaAllowed(uint index)
        {
            bool allowed = true;

            var slides = ExplainViewModel.Instance.Slides;

            for (uint i = 0; i < slides.Length; i++)
            {
                if ((slides[i].MediaType == MediaTypes.AudioOnly ||
                    slides[i].MediaType == MediaTypes.AudioWithImage ||
                    slides[i].MediaType == MediaTypes.Video) && i != index)
                {
                    allowed = false;
                    break;
                }
            }

            return allowed;
        }

        /// <summary>
        /// Binds listbox with list of questions.
        /// </summary>
        /// <param name="listBoxQuestions">Listbox reference.</param>
        private void populateQuestions(ListBox listBoxQuestions)
        {
            List<string> questions = new List<string>();

            questions.Add("What is it?");
            questions.Add("When it is used?");
            questions.Add("Where it is used?");
            questions.Add("Why do we need it?");
            questions.Add("Why does it work in this manner?");
            questions.Add("Is there an example?");
            questions.Add("How does it look?");
            questions.Add("How does it sound like?");
            questions.Add("How does it work?");
            questions.Add("How is it made?");
            questions.Add("How is it used?");

            listBoxQuestions.ItemsSource = questions;
        }

        /// <summary>
        /// Checks if content is valid.
        /// </summary>
        /// <returns>True if content is valid else false.</returns>
        private bool isContentValid()
        {
            string messages = ExplainViewModel.Instance.validateContent();
            bool validContent = messages.Length == 0;

            if (!validContent)
            {
                MessageBox.Show("Please resolve issues mentioned below:" 
                    + Environment.NewLine
                    + Environment.NewLine 
                    + messages);
            }

            return validContent;
        }

        /// <summary>
        /// Occurs when a question is selected for a slide.
        /// </summary>
        /// <param name="sender">List box reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void listQuestion_Tap(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBoxQuestions = ((ListBox)sender);

            uint index = uint.Parse(listBoxQuestions.Tag.ToString());

            // update state
            ExplainViewModel.Instance.Slides[index].Question = listBoxQuestions.SelectedItem.ToString();
        }

        /// <summary>
        /// Occurs when a user chooses audio to answer a question.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void btnAudio_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            uint index = uint.Parse(((Button)sender).Tag.ToString());

            // validate
            if (string.IsNullOrEmpty(ExplainViewModel.Instance.Slides[index].Question))
            {
                MessageBox.Show("Please select a question for slide " + (index + 1));
            }
            else if (!isMoreMediaAllowed(index))
            {
                MessageBox.Show("Only one audio or video can be used in presentation. Multiple audio / video are not supported.");
            }
            else
            {
                // navigate
                NavigationService.Navigate(new Uri("/CreateContentAudio.xaml?index=" + index, UriKind.Relative));
            }
        }

        /// <summary>
        /// Occurs when a user chooses text to answer a question.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void btnText_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            uint index = uint.Parse(((Button)sender).Tag.ToString());

            // validate
            if (string.IsNullOrEmpty(ExplainViewModel.Instance.Slides[index].Question))
            {
                MessageBox.Show("Please select a question for slide " + (index + 1));
            }
            else
            {
                // navigate
                NavigationService.Navigate(new Uri("/CreateContentText.xaml?index=" + index, UriKind.Relative));
            }
        }

        /// <summary>
        /// Occurs when a user chooses video to answer a question.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void btnVideo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            uint index = uint.Parse(((Button)sender).Tag.ToString());

            // validate
            if (string.IsNullOrEmpty(ExplainViewModel.Instance.Slides[index].Question))
            {
                MessageBox.Show("Please select a question for slide " + (index + 1));
            }
            else if (!isMoreMediaAllowed(index))
            {
                MessageBox.Show("Audio or video can be used only once in a presentation. Multiple use of media is not supported.");
            }
            else
            {
                // navigate
                NavigationService.Navigate(new Uri("/CreateContentVideo.xaml?index=" + index, UriKind.Relative));
            }
        }

        /// <summary>
        /// Navigates to view presentation to display its content.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event arguments.</param>
        private void playContent(object sender, EventArgs e)
        {
            if (isContentValid())
            {
                NavigationService.Navigate(new Uri("/ViewPresentation.xaml?view=" + ViewModels.Explain, UriKind.Relative));
            }
        }

        /// <summary>
        /// Navigates to publish presenction to begin publishing the content.
        /// </summary>
        /// <param name="sender">Button reference.</param>
        /// <param name="e">Event specific arguments.</param>
        private void publishContent(object sender, EventArgs e)
        {
            if (isContentValid())
            {
                NavigationService.Navigate(new Uri("/PublishResults.xaml", UriKind.Relative));
            }
        }

        #endregion

        #region Protected members

        /// <summary>
        /// Occurs when page is navigated to, from some other page.
        /// </summary>
        /// <param name="e">Navigation event arguments.</param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // read state and update ui elements
            this.PanSlides.Title = ExplainViewModel.Instance.Term;

            selectQuestionOfSlide(this.listQuestions0, 0);
            selectQuestionOfSlide(this.listQuestions1, 1);
            selectQuestionOfSlide(this.listQuestions2, 2);
        }

        #endregion

        #region Public members
        
        /// <summary>
        /// Initializes new instance of CreateSlides.
        /// </summary>
        public CreateSlides()
        {
            InitializeComponent();

            populateQuestions(listQuestions0);
            populateQuestions(listQuestions1);
            populateQuestions(listQuestions2);
        }

        #endregion
    }
}